<template>
  <div class="light_view">
    <div class="api_table">
      <el-table :data="tableData" border style="width: 100%">
        <el-table-column width="60" type="expand">
          <template #default="props">
            <div m="4">
              <h3
                style="
                  margin-top: 1rem;
                  font-size: 1.35rem;
                  margin-left: 0.5rem;
                "
              >
                请求参数
              </h3>
              <el-table
                :data="props.row.requestParams"
                :border="childBorder"
                stripe
              >
                <el-table-column label="参数名" prop="title" />
                <el-table-column label="备注" prop="notes" />
                <el-table-column label="是否必填" prop="REQUIRED" />
                <el-table-column label="数据类型" prop="type" />
              </el-table>
              <div style="display: flex; align-items: center; margin-top: 1rem">
                <el-button
                  @click="ShowFormBox(props.row)"
                  style="margin-left: 0.5rem"
                >
                  <h3
                    style="
                      font-size: 1.35rem;
                      margin-left: rem;
                      margin-right: 0.5rem;
                    "
                  >
                    请求调用
                  </h3>
                </el-button>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="名称" width="180"></el-table-column>
        <el-table-column
          prop="tags"
          label="请求方式"
          width="180"
          :filters="[
            { text: 'POST', value: 'POST' },
            { text: 'GET', value: 'GET' },
          ]"
          :filter-method="filterTag"
          filter-placement="bottom-end"
        >
          <template #default="scope">
            <el-tag
              :type="scope.row.tags === 'POST' ? '' : 'GET'"
              disable-transitions
              >{{ scope.row.tags }}</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column prop="url" label="接口地址" fit></el-table-column>
        <el-table-column label="操作" width="120">
          <template #default="scope">
            <el-button size="small" @click="ShowFormBox(scope.row)"
              >请求调用</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-dialog
        v-model="isShow"
        :title="apiName"
        width="30%"
        :before-close="handleClose"
      >
        <el-form :model="requestForm">
          <el-form-item
            :label="item.notes"
            v-for="(item, index) in requestForm"
            :key="index"
            label-width="120px"
          >
            <el-input
              v-model="item.value"
              style="width: 240px"
              v-if="item.type != 'datetime' && item.type != 'datetimerange'"
            >
            </el-input>
            <el-date-picker
              v-model="item.value"
              type="datetimerange"
              range-separator="To"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              v-if="item.type == 'datetimerange'"
            />
            <el-date-picker
              v-model="item.value"
              type="datetime"
              range-separator="To"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              v-if="item.type == 'datetime'"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <span>
            <el-button @click="sendRequest()">发送</el-button>
            <el-button @click="isShow = false">关闭</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { ref, toRaw, watch } from "vue";
import { requestApi, fire } from "../apis/projectApis/index";
import { ElMessage } from "element-plus";
import { requestData } from "../assets/js/data";
import { useRoute } from "vue-router";
import axios from "axios";
const childBorder = ref(false);
const route = useRoute();
let dataType = "";
let oldData = [];
let requestForm = ref([]);
const url = ref("");
let apiName = ref("");
const isShow = ref(false);
const tableData = ref([]);
// const bookingTime = ref({})
watch(
  () => route.params,
  (newValue, oldValue) => {
    dataType = newValue.type;
    tableData.value = requestData(dataType);
  },
  { immediate: true }
);
const date = (date) => {
  let result = new Date(date).getTime();
  return result;
};
const handleClose = () => {
  console.log("handleClose");
};
const filterTag = () => {
  console.log("filterTag");
};
const ShowFormBox = async (p) => {
  const startTime = new Date().getTime() + 60000;
  const endTime = startTime + 120000;
  const { name, url, requestParams } = p;
  let res;
  switch (name) {
    case "会议室预约":
      const info = {
        twinID: requestParams[0].value,
        startTime,
        endTime,
      };
      const timeObject = {
        startTime,
        endTime,
      };
      sessionStorage.setItem("fullTime", JSON.stringify(timeObject));
      res = await requestApi(url, info);
      break;
    case "一键会议模式":
      console.log(sessionStorage.getItem("fullTime"));
      let fullTime = JSON.parse(sessionStorage.getItem("fullTime"));
      const Oneinfo = {
        twinID: requestParams[0].value,
        fullTime,
      };
      res = await requestApi(url, Oneinfo);
      localStorage.removeItem("fullTime");
      break;
    case "监控告警推送":
      let alarmInfo = {};
      requestParams.forEach((item) => {
        alarmInfo[item.title] = item.value;
      });
      res = await requestApi(url, alarmInfo);
      break;
    case "停车位监控告警推送":
      let alarmCarInfo = {};
      requestParams.forEach((item) => {
        alarmCarInfo[item.title] = item.value;
      });
      res = await requestApi(url, alarmCarInfo);
      break;
    case "访客到来":
      let requestParams1 = [
        {
          twinID: "停车位_1",
          metric: "车位状态",
          val: "占用",
        },
        {
          twinID: "停车位_1",
          metric: "停车牌号",
          val: "粤d88888",
        },
        {
          twinID: "停车位_1",
          metric: "车辆离开",
          val: 1,
        },
      ];
      res = await axios({
        url: url,
        data: requestParams1,
        method: "POST",
      });
      break;
    case "访客离开车位":
      let requestParams2 = [
        {
          twinID: "停车位_1",
          metric: "车位状态",
          val: "空闲",
        },
        {
          twinID: "停车位_1",
          metric: "停车牌号",
          val: "无车",
        },
        {
          twinID: "停车位_1",
          metric: "车辆离开",
          val: 0,
        },
      ];
      res = await axios({
        url: url,
        data: requestParams2,
        method: "POST",
      });
      break;
    // case "访客到来":
    //   let requestParams3 = [
    //     {
    //       twinID: "停车位_1",
    //       metric: "车位状态",
    //       val: "占用",
    //     },
    //     {
    //       twinID: "停车位_1",
    //       metric: "停车牌号",
    //       val: "粤d888888",
    //     },
    //     {
    //       twinID: "停车位_1",
    //       metric: "车辆离开",
    //       val: 1,
    //     },
    //   ];
    //   res = await axios({
    //     url: url,
    //     data: requestParams3,
    //     method: "POST",
    //   });
    //   break;
    case "天气下雨":
      let requestParams4 = [
        {
          twinID: "云扬园区场景",
          metric: "天气",
          val: "下雨",
        },
      ];
      res = await axios({
        url: url,
        data: requestParams4,
        method: "POST",
      });
      break;
    case "天气晴":
      let requestParams5 = [
        {
          twinID: "云扬园区场景",
          metric: "天气",
          val: "晴天",
        },
      ];
      res = await axios({
        url: url,
        data: requestParams5,
        method: "POST",
      });
      break;
    case "电梯运行7楼":
      let requestParams6 = [
        {
          twinID: "电梯_1",
          metric: "当前楼层",
          val: "F7",
        },
      ];
      res = await axios({
        url: url,
        data: requestParams6,
        method: "POST",
      });
      break;
    case "电梯运行1楼":
      let requestParams7 = [
        {
          twinID: "电梯_1",
          metric: "当前楼层",
          val: "F1",
        },
      ];
      res = await axios({
        url: url,
        data: requestParams7,
        method: "POST",
      });
      break;
    case "着火事件":
      res = await fire();
  }

  if (res.data.code == 200 || res.data.code == -1) {
    ElMessage.success({
      message: apiName.value + "成功",
    });
    if (localStorage.getItem("fullTime")) {
      localStorage.removeItem("fullTime");
    }
  } else {
    ElMessage.error({
      message: apiName.value + "失败",
    });
  }
};

// export NODE_HOME=/var/yyit/node-v18.16.1-linux-x64
// export PATH=$PATH:$NODE_HOME/bin

const sendRequest = async () => {
  isShow.value = false;
  let dataForm = {};
  requestForm.value.forEach((e) => {
    dataForm[toRaw(e).title] = toRaw(e).value;
    if (toRaw(e).type == "datetimerange") {
      let startTime = date(toRaw(e).value)[0];
      console.log(startTime);
      // dataForm[toRaw(e).title] = new Date(toRaw(e).value);
    }
  });
  let res = await requestApi(url.value, dataForm);
  if (res.code == 200) {
    ElMessage.success({
      message: apiName.value + "成功",
    });
  } else {
    ElMessage.error({
      message: apiName.value + "失败",
    });
  }
  toRaw(oldData).forEach((v) => {
    v.value = "";
  });
  requestForm.value = [];
};
</script>

<style lang="scss" scoped>
.light_view {
  width: 100%;
  box-sizing: border-box;
  // padding: 20px;
}
</style>